package com.open.source;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

/**
 * kafka和mq控制切换的管理器
 * <p>跟tax.cloud.mq.selected配置，该配置支持三种场景，
 * 默认所有; tax.cloud.mq.selected=kafka踢除rabbitmq, tax.cloud.mq.selected=rabbitmq踢除kafka
 * <p>
 * 原理通过spring.autoconfigure.exclude配置进行剔除
 * </p>
 *
 * @author ZonLen since on 2022/8/20 上午11:18
 */
public class MqSwitchControlConditionInitializer implements
    ApplicationContextInitializer<ConfigurableApplicationContext> {

  public static final String DEFAULT_MQ_SELECTED = "tax.cloud.mq.selected";
  public static final String RABBIT_MQ = "rabbitmq";
  public static final String KAFKA = "kafka";

  private static final String AUTO_CONFIGURATION_EXCLUDE = "spring.autoconfigure.exclude";


  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
//    final ConfigurableEnvironment environment = applicationContext.getEnvironment();
//    final String mqSelected = environment.getProperty(DEFAULT_MQ_SELECTED);
//    String[] excludes = environment.getProperty(AUTO_CONFIGURATION_EXCLUDE, String[].class);
//    final List<String> excludeAutoConfigurations = new ArrayList<>();
//    if (excludes != null && excludes.length > 0) {
//      excludeAutoConfigurations.addAll(Arrays.asList(excludes));
//    }
//    if (KAFKA.equalsIgnoreCase(mqSelected)) {
//      excludeAutoConfigurations
//          .add("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration");
//    } else {
//      excludeAutoConfigurations
//          .add("org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration");
//    }
//    final Properties source = new Properties();
//    source.put(AUTO_CONFIGURATION_EXCLUDE, excludeAutoConfigurations);
//    environment.getPropertySources()
//        .addFirst(new PropertiesPropertySource(DEFAULT_MQ_SELECTED, source));
  }

}
